{
  MIT License
  Copyright (c) 2024 Lonely
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
}
unit HttpClass;

interface
uses
  HttpInterface,
  SYSTEM.SysUtils,
  System.SyncObjs,
  System.TypInfo,
  System.Classes,
  Net.CrossHttpClient,
  Net.CrossHttpParams,
  Net.CrossHttpUtils,
  Net.OpenSSL,
  Utils.Utils;

type
  THttpBodyFormStream = class(TInterfacedObject,IHttpBodyFormStream)
  protected
    [Weak]FSender:IHttpQuestBase;
    FValue:TStream;
  public
    procedure SetValue(Value:TStream);
    function GetValue:TStream;
    constructor Create(Sender:IHttpQuestBase);
    destructor Destroy; override;
  end;

  THttpBodyBase = class(TInterfacedObject,IHttpBodyBase)
  protected
    [Weak]FSender:IHttpQuestBase;
    FStream:IHttpBodyFormStream;
    FBodyType:TBodyType;
  public
    function GetBodyType:TBodyType;
    function SetBodyType(value:TBodyType):IHttpQuestBase;

    function GetHttpBodyFormStream:TStream;
    function SetHttpBodyFormStream(value:TStream):IHttpQuestBase;
    function SetHttpBodyFormString(value:string):IHttpQuestBase;
    constructor Create(Sender:IHttpQuestBase);
    destructor Destroy; override;
  end;

  THttpHeaderBase = class(TInterfacedObject,IHttpHeaderbase)
  protected
    [Weak]FSender:IHttpQuestBase;
    FHttpHeaders: THttpHeader;
  public
    function Add(const AName, AValue: string; ADupAllowed: Boolean = False):IHttpQuestBase;overload;
    function Add(const AEncodedParams: string):IHttpQuestBase;overload;
    function Remove(const AName: string):IHttpQuestBase;
    function ExistsParam(const AName: string): Boolean;
    function GetParamValue(const AName: string; out AValue: string):Boolean;
    function Clear: IHttpQuestBase;

    function SetReferer(Value:string):IHttpQuestBase;
    function SetContentType(Value:string):IHttpQuestBase;
    function SetCookie(Value:string):IHttpQuestBase;

    function Encode: string;
    constructor Create(Sender:IHttpQuestBase);
    destructor Destroy; override;
  end;

  THttpQuestBase = class(TInterfacedObject,IHttpQuestBase)
  protected
    fUrl:string;
    fMethod:string;
    FHttpCli: ICrossHttpClient;
    FHttpHeaders: IHttpHeaderBase;
    FHttpBodys:IHttpBodyBase;
    procedure DefaultAddHeader(const AName, AValue: string);
    procedure SetDefaultHeader;
  public
    function GetUrl:string;virtual;
    function GetMethod:string;virtual;
    function SetUrl(value:string):IHttpQuestBase;virtual;
    function SetMethod(value:string):IHttpQuestBase;virtual;
    function AddHeader(const AName, AValue: string; ADupAllowed: Boolean = False):IHttpQuestBase;virtual;
    function HttpHeaders: IHttpHeaderBase;virtual;
    function HttpBodys:IHttpBodyBase;virtual;
    function Execute(const AInitProc: TCrossHttpRequestInitProc;const ACallback: TCrossHttpResponseProc):Boolean;overload;virtual;
    function Execute():ICrossHttpClientResponse;overload;virtual;
    constructor Create(AHttpCli: ICrossHttpClient);
    destructor Destroy; override;
  end;

{ THttp }

  THttp = class(TInterfacedObject,IHttpBase)
  private
    FHttpCli: ICrossHttpClient;
  protected

  public
    function Execute:IHttpQuestBase;
    constructor Create;
    destructor Destroy; override;
  published

  end;

function StringToStream(Value:string):TStream;
implementation


{ THttpQuestBase<T> }
function StringToStream(Value:string):TStream;
begin
  Result := TStringStream.Create;
  TStringStream(Result).WriteString(Value);
  TStringStream(Result).Position := 0;
end;

function THttpQuestBase.AddHeader(const AName, AValue: string;
  ADupAllowed: Boolean): IHttpQuestBase;
begin
  FHttpHeaders.Add(AName,AValue,ADupAllowed);
end;

constructor THttpQuestBase.Create(AHttpCli: ICrossHttpClient);
begin
  FHttpCli := AHttpCli;
  FHttpHeaders := THttpHeaderBase.Create(Self);
  FHttpBodys := THttpBodyBase.Create(Self);
end;

procedure THttpQuestBase.DefaultAddHeader(const AName, AValue: string);
begin
  if not FHttpHeaders.ExistsParam(AName) then
    AddHeader(AName,AValue);
end;

procedure THttpQuestBase.SetDefaultHeader;
begin
  DefaultAddHeader(HEADER_USER_AGENT,DefaultUserAgent);
  DefaultAddHeader(HEADER_CONTENT_TYPE,TMediaType.APPLICATION_FORM_URLENCODED_TYPE);
end;

destructor THttpQuestBase.Destroy;
begin
  FHttpCli := nil;
  FHttpBodys := nil;
  FHttpHeaders := nil;
  inherited;
end;

function THttpQuestBase.Execute: ICrossHttpClientResponse;
var
  LRESULT: ICrossHttpClientResponse;
  Event:TEvent;
begin
  Event := TEvent.Create(False);
  Execute(nil,procedure(const AResponse: ICrossHttpClientResponse)
                begin
                  LRESULT := AResponse;
                  Event.SetEvent;
                end
                );
  Event.WaitFor();

  Result := LRESULT;
end;

function THttpQuestBase.Execute(const AInitProc: TCrossHttpRequestInitProc;
    const ACallback: TCrossHttpResponseProc):Boolean;
var
  lhttpheader:THttpHeader;
begin
  Self._AddRef;
  Result := False;
  try
    lhttpheader := THttpHeader.Create(FHttpHeaders.Encode);
    if HttpBodys.GetBodyType = body_nil then
    begin

      FHttpCli.DoRequest(
                        GetMethod,
                        GetUrl,
                        lhttpheader,
                        nil,0,
                        nil,
                        procedure(const ARequest: ICrossHttpClientRequest)
                        begin
                          if Assigned(AInitProc) then
                            AInitProc(ARequest);
                        end,
                        procedure(const AResponse: ICrossHttpClientResponse)
                        begin
                          if Assigned(ACallback) then
                            ACallback(AResponse);
                          lhttpheader.Free;
                          Self._Release;
                        end
                        )
    end
    else
    if HttpBodys.GetBodyType = body_stream then
    begin
      FHttpCli.DoRequest(
                        GetMethod,
                        GetUrl,
                        lhttpheader,
                        HttpBodys.GetHttpBodyFormStream,
                        nil,
                        procedure(const ARequest: ICrossHttpClientRequest)
                        begin
                          if Assigned(AInitProc) then
                            AInitProc(ARequest);
                        end,
                        procedure(const AResponse: ICrossHttpClientResponse)
                        begin
                          if Assigned(AResponse) then
                            ACallback(AResponse);

                          lhttpheader.Free;
                          Self._Release;
                        end
                        );
    end;
  except
    on E: Exception do
      raise E;
  end;

  Result := True;

end;

function THttpQuestBase.GetMethod: string;
begin
  Result := fMethod;
end;

function THttpQuestBase.GetUrl: string;
begin
  Result := fUrl;
end;

function THttpQuestBase.HttpBodys: IHttpBodyBase;
begin
  Result := FHttpBodys;
end;

function THttpQuestBase.HttpHeaders: IHttpHeaderBase;
begin
  Result := fHttpHeaders;
end;

function THttpQuestBase.SetMethod(value: string): IHttpQuestBase;
begin
  fMethod := value;
  Result := Self;
end;

function THttpQuestBase.SetUrl(value: string): IHttpQuestBase;
begin
  fUrl := value;
  Result := Self;
end;


{ THttpHeaderBase }

function THttpHeaderBase.Add(const AName, AValue: string;
  ADupAllowed: Boolean): IHttpQuestBase;
begin
  FHttpHeaders.Add(AName,AValue,ADupAllowed);
  Result := FSender;
end;

function THttpHeaderBase.Add(const AEncodedParams: string): IHttpQuestBase;
begin
  FHttpHeaders.Add(AEncodedParams);
  Result := FSender;
end;

function THttpHeaderBase.Clear: IHttpQuestBase;
begin
  FHttpHeaders.Clear;
  Result := FSender;
end;

constructor THttpHeaderBase.Create(Sender:IHttpQuestBase);
begin
  FHttpHeaders := THttpHeader.Create;
  FSender := Sender;
end;

destructor THttpHeaderBase.Destroy;
begin
  FreeAndNil(FHttpHeaders);
  inherited;
end;

function THttpHeaderBase.Encode: string;
begin
  Result := FHttpHeaders.Encode;
end;

function THttpHeaderBase.ExistsParam(const AName: string): Boolean;
begin
  Result := FHttpHeaders.ExistsParam(AName);
end;

function THttpHeaderBase.GetParamValue(const AName: string;
  out AValue: string): Boolean;
begin
  result := FHttpHeaders.GetParamValue(AName,AValue);
end;

function THttpHeaderBase.Remove(const AName: string):IHttpQuestBase;
begin
  FHttpHeaders.Remove(AName);
  Result := FSender;
end;

function THttpHeaderBase.SetContentType(Value: string): IHttpQuestBase;
begin
  FHttpHeaders.Add(HEADER_CONTENT_TYPE ,Value,False);
  Result := FSender;
end;

function THttpHeaderBase.SetCookie(Value: string): IHttpQuestBase;
begin
  FHttpHeaders.Add(HEADER_COOKIE ,Value,False);
  Result := FSender;
end;

function THttpHeaderBase.SetReferer(Value: string): IHttpQuestBase;
begin
  FHttpHeaders.Add(HEADER_REFERER ,Value,False);
  Result := FSender;
end;

{ THttpBodyBase }

constructor THttpBodyBase.Create(Sender: IHttpQuestBase);
begin
  FStream := THttpBodyFormStream.Create(Sender);
  FSender := Sender;
  FBodyType := body_nil;
end;

destructor THttpBodyBase.Destroy;
begin
  FSender := nil;
  FStream := nil;
  inherited;
end;

function THttpBodyBase.GetBodyType: TBodyType;
begin
  Result := FBodyType;
end;

function THttpBodyBase.GetHttpBodyFormStream: TStream;
begin
  Result := FStream.Value;
end;


function THttpBodyBase.SetBodyType(value: TBodyType):IHttpQuestBase;
begin
  FBodyType := value;
  Result := FSender;
end;

function THttpBodyBase.SetHttpBodyFormStream(value: TStream):IHttpQuestBase;
begin
  FStream.Value := value;
  FBodyType := body_stream;
  Result := FSender;
end;

function THttpBodyBase.SetHttpBodyFormString(value: string): IHttpQuestBase;
begin
  Result := SetHttpBodyFormStream(StringToStream(value));
end;

{ THttpBodyFormStream }

constructor THttpBodyFormStream.Create(Sender: IHttpQuestBase);
begin
  FSender := Sender;
end;

destructor THttpBodyFormStream.Destroy;
begin
  if FValue <> nil then
    FreeAndNil(FValue);
  inherited;
end;

function THttpBodyFormStream.GetValue: TStream;
begin
   Result := FValue;
end;

procedure THttpBodyFormStream.SetValue(Value: TStream);
begin
   FValue := Value;
end;

{ THttp }

constructor THttp.Create;
begin
  FHttpCli := TCrossHttpClient.Create(4,ctNone);
end;

destructor THttp.Destroy;
begin
  FHttpCli := nil;
  inherited;
end;

function THttp.Execute: IHttpQuestBase;
begin
  Result := THttpQuestBase.Create(FHttpCli);
end;

end.
